/** 注释
 * @Name index;
 * @Author FiveXu
 * @Description index
 * @Date 2023-01-08 15:45
 */
import { onBeforeUnmount, onMounted, ref } from 'vue'

export const useScroll = (cb?: (val: boolean) => void) => {
  // 是否开启
  const isStart = ref<boolean>(false)
  // dom
  const triggerDom = ref<HTMLElement>()

  // 滚动条监听
  const handleScroll = () => {
    if (!triggerDom.value) return
    const scrollTop = document.documentElement.scrollTop
    const top = triggerDom.value.offsetTop
    isStart.value = scrollTop >= top - (innerHeight * 2) / 3
    if (cb && typeof cb === 'function') cb(isStart.value)
  }

  onMounted(() => {
    document.addEventListener('scroll', handleScroll)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('scroll', handleScroll)
  })

  return {
    triggerDom,
    isStart
  }
}
